package signGrammar.view;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JButton;

public class CViewStateButton extends JButton{
	private static final long serialVersionUID = -7208764630992441602L;
	
	public interface IStateButtonListener {
		public void stateChanged( String oldState, String newState );
	}
	
	private final String[] states;
	private int currentState = 0;
	public CViewStateButton(String... states) {
		this.states = states;
		super.setText( states[0] );
		this.addActionListener(new ActionListener(){
			@Override public void actionPerformed(ActionEvent e) {
				stateChaneged();
			}});
	}

	private void stateChaneged(){
		String current = states[ currentState ];
		String nextOne = nextState();
		for( IStateButtonListener s: stateButtonListeners )
			s.stateChanged(current, nextOne);
	}
		
	public String nextState(){
		currentState = currentState+1 < states.length ? ++currentState : 0;
		super.setText( currentState() );
		return currentState();
	}
	
	public String currentState(){
		return states[ currentState ];
	}
	
	public CViewStateButton setState( String state ){
		int index = -1;
		if( (index = find(state)) >= 0 ){
			currentState = index;
			super.setText( states[ currentState ] );
		}
		return this;
	}
	
	@Override
	public void setText(String s){
		setState(s);
	} 
	
	private int find(String state){
		for( int i=0; i < states.length; i++ )
			if( states[i].equals( state ) )
				return i;
		return -1;
	}
	
	protected ArrayList<IStateButtonListener> stateButtonListeners = new ArrayList<IStateButtonListener>();
	public CViewStateButton addListener( IStateButtonListener list ){
		stateButtonListeners.add(list);
		return this;
	}
	public boolean removeListener(IStateButtonListener list){
		return stateButtonListeners.remove(list);
	}
}
